﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Web;

namespace X.Security
{
    public class ManageCookies
    {
        public static void CreateUserCookie(FormsAuthenticationTicket authTicket, bool isPersistent, DateTime expirationTime)
        {
            CreateCookie(FormsAuthentication.FormsCookieName + "UserCookie", authTicket, isPersistent, expirationTime);
        }

        public static void CreateCookie(string cookieName, FormsAuthenticationTicket authTicket, bool isPersistent, DateTime expirationTime)
        {
            string str = FormsAuthentication.Encrypt(authTicket);
            HttpCookie cookie = new HttpCookie(cookieName, str);
            if (isPersistent)
                cookie.Expires = expirationTime;
            cookie.HttpOnly = true;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Secure = FormsAuthentication.RequireSSL;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        private static void RemoveCookie(string cookieName)
        {
            string str = string.Empty;
            if (HttpContext.Current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
                str = "NoCookie";
            HttpCookie cookie = new HttpCookie(cookieName, str);
            cookie.HttpOnly = true;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Expires = new DateTime(2012, 9, 24);
            cookie.Secure = FormsAuthentication.RequireSSL;
            HttpContext.Current.Response.Cookies.Remove(cookieName);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static void RemoveUserCookie()
        {
            RemoveCookie(FormsAuthentication.FormsCookieName + "UserCookie");
        }
    }
}
